package cn.xiaobai.captcha.utils;

import cn.xiaobai.captcha.enums.OperatorEnum;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


/**
 * @author yangdaji
 * @version 1.0
 * @Description: 针对一个算术字符串进行计算
 * 例:
 * "1+2=?" 进行计算成对应的结果:
 * 1+2=3 得到结果 3
 * @date 22-6-11 下午 11:37
 */
public class MathCaptchaResultUtils {

    /**
     * 计算算术字符串脚本,只计算整数,小数会丢失精度
     *
     * @param mathCaptcha 算术字符串
     * @return
     */
    public static String captchaMathResult(String mathCaptcha) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {
            return engine.eval(convertToOperator(mathCaptcha)).toString();
        } catch (ScriptException e) {
            throw new RuntimeException("算术字符串格式有误: " + e.getMessage());
        }
    }

    /**
     * 运算符转换
     *
     * @param aliasOperator
     * @return
     */
    public static String convertToOperator(String aliasOperator) {
        aliasOperator = aliasOperator.substring(0, aliasOperator.lastIndexOf("="));
        char[] chars = aliasOperator.toLowerCase().toCharArray();
        String value = aliasOperator;
        for (char aChar : chars) {
            if (isOperator(aChar)) {
                String charToString = Character.toString(aChar).trim();
                String operator = OperatorEnum.getOperator(charToString);
                value = aliasOperator.replaceAll(charToString, operator);
            }
        }
        return value;
    }

    /**
     * 判断是否为算术符号
     *
     * @param c
     * @return
     */
    private static boolean isOperator(char c) {
        //c == '+' ||
        return  c == '-' || c == '*' || c == '/' || c == '(' || c == ')' || c == 'x' || c == '÷';
    }


}
